﻿using Entity;
using Essensoft.Paylink.WeChatPay;
using Essensoft.Paylink.WeChatPay.V3;
using Essensoft.Paylink.WeChatPay.V3.Notify;
using Furion.EventBus;
using Microsoft.Extensions.Options;

namespace Services;

/// <summary>
/// 通知记录
/// </summary>
[ApiDescriptionSettings("支付")]
public class NotifyServices : BaseServices
{
    #region 注入

    private readonly IEventPublisher pub;

    private readonly ISqlSugarClient db;

    private readonly IWeChatPayNotifyClient wechat;

    private readonly IOptions<WeChatPayOptions> options;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="pub"></param>
    /// <param name="db"></param>
    /// <param name="wechat"></param>
    /// <param name="options"></param>
    public NotifyServices(IEventPublisher pub, ISqlSugarClient db, IWeChatPayNotifyClient wechat, IOptions<WeChatPayOptions> options)
    {
        this.pub = pub;
        this.db = db;
        this.wechat = wechat;
        this.options = options;
    }




    #endregion

    /// <summary>
    /// 支付通知
    /// </summary>
    /// <returns></returns>
    public async Task<object> WechatPay()
    {
        try
        {
            var notify = await wechat.ExecuteAsync<WeChatPayTransactionsNotify>(App.HttpContext.Request, options.Value);

            if (notify.TradeState == WeChatPayTradeState.Success)
            {
                await pub.PublishAsync("OrderComplete", new Events.Dto.OrderComplete
                {
                    OrderNo = notify.OutTradeNo,

                    ThreeOrderNo = notify.TransactionId,

                    PayType = PayType.微信
                });

                await pub.PublishDelayAsync("SubWechatOrder", 10000, new Events.Dto.SubWechatOrderDto { OrderNo = notify.OutTradeNo, OpenId = notify.Payer.OpenId, Type = 3, GoodsInfo = "" });

                return WeChatPayNotifyResult.Success;
            }

            return WeChatPayNotifyResult.Failure;
        }
        catch (WeChatPayException)
        {
            return WeChatPayNotifyResult.Failure;
        }
    }


    /// <summary>
    /// 退款通知
    /// </summary>
    /// <returns></returns>
    public async Task<object> WechatRefund()
    {
        try
        {
            var notify = await wechat.ExecuteAsync<WeChatPayRefundDomesticRefundsNotify>(App.HttpContext.Request, options.Value);

            if (notify.RefundStatus == WeChatPayRefundStatus.Success)
            {
                return WeChatPayNotifyResult.Success;
            }

            return WeChatPayNotifyResult.Failure;
        }
        catch (WeChatPayException)
        {
            return WeChatPayNotifyResult.Failure;
        }
    }
}
